#include <stdbool.h>
#include <stddef.h>
#include "stm32f4xx.h"
#include "FreeRTOS.h"
#include "task.h"
#include "esp_at.h"
#include "lcd.h"
#include "image.h"

#define LOG_TAG "wifi"
#define LOG_LVL ELOG_LVL_INFO
#include "elog.h"

#define YOUR_WIFI_NAME "MEIZU 21"
#define YOUR_WIFI_PASS "88888888"

void wifi_wait_connect(void)
{
    log_i("wifi connecting");

    esp_wifi_connect(YOUR_WIFI_NAME, YOUR_WIFI_PASS, NULL);

    for (uint32_t i = 0; i < 10 * 1000; i += 100)
    {
        vTaskDelay(pdMS_TO_TICKS(100));
        esp_wifi_info_t wifi = {0};
        if (esp_at_get_wifi_info(&wifi) && wifi.connected)
        {
            log_i("wifi connected");
            printf("SSID: %s, BSSID: %s, Channel: %d, RSSI: %d\n",
                wifi.ssid, wifi.bssid, wifi.channel, wifi.rssi);
            return;
        }
    }

    log_e("connection timeout");
    err_404_image_display("wifi connect faild");
    while (1);
}

void wifi_init(void)
{
    if(!esp_wifi_init())
    {
        log_e("wifi init faild");
        goto err;
    }
    if(!esp_wifi_connect(YOUR_WIFI_NAME, YOUR_WIFI_PASS, NULL))
    {
        log_e("wifi connect faild");
        goto err;
    }
    if(!esp_at_sntp_init())
    {
        log_e("wifi sntp faild");
        goto err;
    }

    log_i("inited");
    return;

err:
    err_404_image_display("wifi init faild");
    while (1);
}
